from flask import Blueprint, render_template, session, request, redirect, url_for
from werkzeug.security import check_password_hash, generate_password_hash

from models import *
import math

global  borrowlist

usr = Blueprint("usr", __name__, url_prefix="/usr")


@usr.route('/center')
def center():
    username = session['user_name']
    user = UserModel.query.filter_by(username=username).first()
    return render_template("user-self-center.html", usr=user)


@usr.route('/borrow/<isbn>', methods=['POST'])
def borrow(isbn):
    username = session["user_name"]
    # bookisbn = request.values.get("bookisbn")
    bookisbn = isbn
    user = UserModel.query.filter_by(username=username).first()
    book = BookModel.query.filter_by(bookisbn=bookisbn).first()
    user.borrow.append(book)
    book.remainder -= 1
    db.session.commit()
    # result = db.session.query(tb_user_borrow).filter_by(user_id=user.id, book_isbn=bookisbn).first()
    # print(type(result))
    # result[4] = username
    # sql = "UPDATE `user_borrow` SET user_name = '"+username+"' WHERE user_id="+str(user.id)+" AND book_isbn='"+bookisbn+"';"
    # print(sql)
    result = db.session.query(tb_user_borrow).filter_by(user_id=user.id, book_isbn=bookisbn).update({"user_name":username})
    # db.session.execute(sql)
    db.session.commit()
    print("借阅成功!")
    return redirect(url_for("book_manage.books_getall"))


@usr.route('/myborrow')
def my_borrow():
    global borrowlist
    username = session['user_name']
    user = UserModel.query.filter_by(username=username).first()
    borrowlist = list(user.borrow)
    session['myborrownum'] = len(borrowlist)
    session['myborrowpages'] = math.ceil(session['myborrownum'] / 10)
    myborrow = borrowlist[:10]
    isback = {}
    borrowtime = {}
    for x in myborrow:
        a = db.session.query(tb_user_borrow).filter_by(user_id=user.id, book_isbn=x.bookisbn).first()
        borrowtime[x.bookisbn] = a.borrowtime
        if a.isback == 1:
            isback[x.bookisbn] = 1
        else:
            isback[x.bookisbn] = 0
    return render_template("reader-borrow.html", nowpage=1, myborrow=myborrow, isback=isback, time=borrowtime, now=datetime.now())


@usr.route('/turn/<page>', methods=['GET'])
def turn_page(page):
    username = session['user_name']
    user = UserModel.query.filter_by(username=username).first()
    page = int(page)
    max_num = min(session['myborrownum'], (page*10))
    global  borrowlist
    myborrow = borrowlist[(page-1) * 10:max_num]
    isback = {}
    borrowtime = {}
    for x in myborrow:
        a = db.session.query(tb_user_borrow).filter_by(user_id=user.id, book_isbn=x.bookisbn).first()
        borrowtime[x.bookisbn] = a.borrowtime
        if a.isback == 1:
            isback[x.bookisbn] = 1
        else:
            isback[x.bookisbn] = 0
    return render_template("reader-borrow.html", nowpage=1, myborrow=myborrow, isback=isback, time=borrowtime,
                           now=datetime.now())


@usr.route('/jump', methods=['POST'])
def jump_page():
    page = request.values.get('page')
    return turn_page(page)


@usr.route('/giveback/<iid>/<isbn>', methods=['POST'])
def give_back(iid, isbn):
    result = db.session.query(tb_user_borrow).filter_by(user_id=iid, book_isbn=isbn).update({"isback": 1})
    book = BookModel.query.filter_by(bookisbn=isbn).first()
    name = session['user_name']
    user = UserModel.query.filter_by(username=name).first()
    user.borrow.remove(book)
    book.remainder += 1
    db.session.commit()
    return my_borrow()


@usr.route('/change', methods=['POST'])
def change_info():
    username = session['user_name']
    user = UserModel.query.filter_by(username=username).first()
    nick = request.values.get('nickname')
    school = request.values.get('school')
    phone = request.values.get('phonenum')
    print(nick)
    print(school)
    print(phone)
    if nick != None:
        user.nickname = nick
    if school != None:
        user.school = school
    if phone != None:
        user.phone = phone
    db.session.commit()
    return center()


@usr.route('/change_pass', methods=['POST'])
def change_pass():
    origin = request.values.get('origin')
    password = request.values.get('password')
    username = session['user_name']
    user = UserModel.query.filter_by(username=username).first()
    print(username)
    if check_password_hash(user.password, origin):
        user.password = generate_password_hash(password)
        db.session.commit()
        return center()
    else:
        return "error"
